<?php

namespace App\Store\Controllers\Login;

use App\Admin\Models\SiteCompany;
use Illuminate\Http\Request;

use App\Http\Controllers\Controller;
use App\Store\Models\Account\Account;
use App\Common\Services\Store\Common;
use App\Store\Services\Log\LogLogin;
use Illuminate\Support\Facades\Redis;

class LoginController extends Controller
{

    /**
     * 门店登陆
     */
    public function dologin(Request $request)
    {
        try {
            $this->validate($request, [
                'account_name' => 'required',
                'password' => 'required',
            ]);
        } catch (\Exception $exception) {
            return response()->json(['code' => '001', 'msg' => '帐号或者密码不能为空']);
        }
        if (strlen($request->password) != 32) {
            return response()->json(['code' => '001', 'msg' => '密码长度不规范']);
        }
        $info = Account::where('account_name', $request->account_name)
//         ->where('is_del',1)
            // ->where('password', MD5($request->password))
            ->orderby('id', 'desc')
            ->first();
        if ($info) {
            if ($info->is_del != 1) {
                LogLogin::savelog($request, 2, $info->cp_id, $info->id);
                return response()->json(['code' => '001', 'msg' => '无效账号']);
            }
            if ($info->status != 1) {

                LogLogin::savelog($request, 2, $info->cp_id, $info->id);
                return response()->json(['code' => '001', 'msg' => '账号已被禁用']);
            }
            if ($info->password != MD5($request->password)) {
                LogLogin::savelog($request, 2, $info->cp_id, $info->id);
                return response()->json(['code' => '001', 'msg' => '帐号或者密码错误']);
            }

            $storetoken = md5(time() . mt_rand(1000, 9999) . '__' . $info->id);

            //判断访问来源
            if (strpos(strtolower($request->header('user-agent')), 'miniprogram') !== false || strpos(strtolower($request->header('user-agent')), 'wechatdevtools') !== false || strpos(strtolower($request->header('user-agent')), 'micromessenger') !== false) {
                if ($info->is_wxapp_login != 1) {
                    return response()->json(['code' => '001', 'msg' => '未开启小程序登录权限']);
                }

                Redis::setex($storetoken, (strtotime(date('Y-m-d') . ' 23:59:59') - time()), json_encode($info));
                Common::storetokenkeybywxapp($storetoken, $info->id);
            } else {
                Redis::set($storetoken, json_encode($info));
                Common::storetokenkey($storetoken, $info->id);
            }

            Account::where(['id' => $info->id])->update(['lastlogin_ip' => $request->ip(), 'lastlogin_at' => time()]);
            $info = $info->toArray();
            unset($info['password']);
            LogLogin::savelog($request, 1, $info['cp_id'], $info['id']);

            $company = SiteCompany::query()->where(['id' => $info['cp_id']])->first();
            if (empty($company)) {
                return response()->json(['code' => '001', 'msg' => '该账号无对应的公司']);
            }
            $company = $company->toArray();

            $info['is_finance'] = $company['is_finance'] ?? 2;
            $info['is_training'] = $company['is_training'] ?? 2;

            $is_locked = Redis::get('LOCKINFO_' . $info['cp_id']);
            if (intval($is_locked) <= 0) {
                $is_locked = $company['is_locked'] ?? 0;
                Redis::set('LOCKINFO_' . $info['cp_id'], $is_locked);
            }

            return response()->json(['code' => '000', 'msg' => '登录成功', 'data' => ['storetoken' => $storetoken, 'info' => $info], 'is_locked' => $is_locked]);
        } else {
            LogLogin::savelog($request, 2);
            return response()->json(['code' => '001', 'msg' => '帐号或者密码错误']);
        }
    }

    /**
     * 门店退出登录
     */
    public function dologinout(Request $request)
    {
        $storetoken = $request->header('storetoken');
        $accountinfo = Redis::get($storetoken);
        if (!$storetoken || !$accountinfo) {
            return response()->json(['code' => '001', 'msg' => '非法访问']);
        }
        $accountinfo = json_decode($accountinfo, true);
        $info = Account::where(['id' => $accountinfo['id']])->first();
        if (!$info) {
            return response()->json(['code' => '001', 'msg' => '无效参数']);
        }

        Redis::delete($storetoken);
        return response()->json(['code' => '000', 'msg' => '操作成功']);
    }

    /**
     * 门店更改密码
     */
    public function changepassword(Request $request)
    {
        $storetoken = $request->header('storetoken');
        $accountinfo = Redis::get($storetoken);
        if (!$storetoken || !$accountinfo) {
            return response()->json(['code' => '001', 'msg' => '非法访问']);
        }


        $accountinfo = json_decode($accountinfo, true);
        $info = Account::where(['id' => $accountinfo['id']])->first();
        if (!$info) {
            return response()->json(['code' => '001', 'msg' => '无效参数']);
        }
        $oldpassword = $request->oldpassword;
        $password = $request->password;
        $repassword = $request->repassword;
        if ((strlen($oldpassword) < 5 || strlen($oldpassword) > 20) || (strlen($password) < 5 || strlen($password) > 20) || (strlen($repassword) < 5 || strlen($repassword) > 20)) {
            return response()->json(['code' => '001', 'msg' => '请保持密码长度为5~20位']);
        }

        if ($oldpassword == '' || $password == '' || $repassword == '' || $password != $repassword) {
            return response()->json(['code' => '001', 'msg' => '请确保输入框完整']);
        }


        if (MD5(MD5('zhuxiaobao_' . $oldpassword)) != $info->password) {
            return response()->json(['code' => '001', 'msg' => '原密码不正确']);
        }

        Account::where(['id' => $accountinfo['id']])->update(['password' => MD5(MD5('zhuxiaobao_' . $password))]);

        //清除缓存
        Common::cleartokenkey($accountinfo['id']);
        Common::cleartokenkeybywxapp($accountinfo['id']);
        return response()->json(['code' => '000', 'msg' => '操作成功']);
    }


}
